package com.ihome.android.academy;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.CheckBox;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import com.ihome.android.EAActivity;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.adapter.FragmentAdapter;
import com.ihome.android.market2.asynctask.GetAlbumTitleTask;
import com.ihome.android.market2.frag.RecommAppFragment;
import com.ihome.android.market2.info.TemplateContentInfo;
import com.ihome.android.market2.view.DepthPageTransformer;
import com.ihome.android.market2.view.FixedScroller;
import com.ihome.android.market2.view.LogoTop;
import com.ihome.android.util.log.LogUtil;

public class AlbumActivity extends EAActivity {
	private String					TAG					= AlbumActivity.class.getSimpleName();

	private Context					mContext;
	@EAInjectView(id = R.id.user_topline)
	private LogoTop					user_topline;
	@EAInjectView(id = R.id.hs_title)
	private HorizontalScrollView	hs_title;
	/** 一级导航栏 */
	@EAInjectView(id = R.id.ll_title)
	private LinearLayout			ll_title;
	@EAInjectView(id = R.id.vp_fragment)
	private ViewPager				vp_fragment;

	private List<TemplateContentInfo> mCategoryList;
	private List<Fragment>			mFraglist;
	private int						curPosition			= 0;
	private int						totalPage;

	private final int				MSG_CHANGE_POSITION	= 11;
	
	private int						sectionId	= 0;

	private Handler					mHandler;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_CHANGE_POSITION:
					int titlePos = (Integer) msg.obj;
					if (titlePos != curPosition) {
						titleSelected(titlePos);
						vp_fragment.setCurrentItem(titlePos);
					}
					break;
				default:
					break;
				}
			}
		};
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_new);
		procHandler();
		mContext = AlbumActivity.this;
		sectionId = getIntent().getExtras().getInt(HttpKeys.KEY_SECTIONID);
		LogUtil.d(TAG, "onCreate() --> sectionId = " + sectionId);
		
		if(sectionId > 0){
			Bundle b = new Bundle();
			b.putInt(HttpKeys.KEY_SECTIONID, sectionId);
			new GetAlbumTitleTask(AlbumActivity.this).execute(b);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_DPAD_UP && event.getAction() == KeyEvent.ACTION_DOWN && vp_fragment.hasFocus() && (mFraglist.get(curPosition) instanceof RecommAppFragment)
				&& ((RecommAppFragment) mFraglist.get(curPosition)).isAtTop()) {
			titleFocus();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void move2Next() {
		if (curPosition + 1 <= totalPage)
			vp_fragment.setCurrentItem(curPosition + 1);
	}

	public void move2Previou() {
		if (curPosition - 1 >= 0)
			vp_fragment.setCurrentItem(curPosition - 1);
	}

	public void move2First() {
		LogUtil.d(TAG, "move2First() --> ");
		vp_fragment.setCurrentItem(0);
	}

	public void move2Last() {
		LogUtil.d(TAG, "move2Last() --> ");
		vp_fragment.setCurrentItem(totalPage - 1);
	}

	private void titleSelected(int position) {
		((CheckBox) ((LinearLayout) ll_title.getChildAt(position)).getChildAt(0)).setChecked(true);

		for (int i = 0; i < ll_title.getChildCount(); i++) {
			if (i != position) {
				((CheckBox) ((LinearLayout) ll_title.getChildAt(i)).getChildAt(0)).setChecked(false);
			}
		}
	}

	public void titleFocus() {
		if (ll_title != null)
			ll_title.getChildAt(curPosition).requestFocus();
	}

	public void initTitle(List<TemplateContentInfo> titleList) {
		mCategoryList = titleList;
		int size = titleList.size();
		for (int i = 0; i < size; i++) {
			TemplateContentInfo info = titleList.get(i);
			info.setPosition(i);
			View mTitleItem = LayoutInflater.from(mContext).inflate(R.layout.title_item, null);
			mTitleItem.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1));
			final CheckBox checkbox = (CheckBox) mTitleItem.findViewById(R.id.cb_item);
			checkbox.setText(info.getName());
			checkbox.setPadding(10, 5, 10, 5);
			checkbox.setTag(info);

			checkbox.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {

					if (hasFocus) {
						TemplateContentInfo infotv = (TemplateContentInfo) v.getTag();
						LogUtil.v(TAG, " -->  onFocusChange() position = " + infotv.getPosition() + "; Name = " + infotv.getName());
						mHandler.removeMessages(MSG_CHANGE_POSITION);
						mHandler.sendMessage(Message.obtain(mHandler, MSG_CHANGE_POSITION, infotv.getPosition()));
					}
				}
			});

			ll_title.addView(mTitleItem);
		}

		initViewPage();
		titleFocus();
	}

	private void initViewPage() {
		mFraglist = new ArrayList<Fragment>();

		for (TemplateContentInfo info : mCategoryList) {
			RecommAppFragment appViewFragment = new RecommAppFragment();
			Bundle b = new Bundle();
			b.putInt(HttpKeys.KEY_SECTIONID, info.getContentId());
			appViewFragment.setArguments(b);
			mFraglist.add(appViewFragment);
		}

		totalPage = mFraglist.size();
		vp_fragment.setAdapter(new FragmentAdapter(getSupportFragmentManager(), mFraglist));
		vp_fragment.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageSelected(int position) {
				curPosition = position;
				titleSelected(position);
				LogUtil.v(TAG, " -->  onPageSelected() ID = " + mCategoryList.get(position).getContentId() + "; Name = " + mCategoryList.get(position).getName() + "; curPosition = "
						+ curPosition);

			}

		});

		vp_fragment.setOffscreenPageLimit(totalPage);
		vp_fragment.setCurrentItem(0);
		initVPAnim();
	}

	private void initVPAnim() {
		try {
			Field mScroller;
			mScroller = ViewPager.class.getDeclaredField("mScroller");
			mScroller.setAccessible(true);
			Interpolator sInterpolator = new AccelerateDecelerateInterpolator();
			FixedScroller scroller = new FixedScroller(vp_fragment.getContext(), sInterpolator);
			mScroller.set(vp_fragment, scroller);
		} catch (Exception e) {
			e.printStackTrace();
		}

		//vp_fragment.setPageTransformer(true, new ZoomOutPageTransformer());
		vp_fragment.setPageTransformer(true, new DepthPageTransformer());

	}

	/**
	 * 
	 * 设置需要升级的APP List数量
	 * 
	 * @param num
	 *            -- 需要升级的APP数量
	 * @see [类、类#方法、类#成员]
	 */
	public void checkNeedUpdateApp(int num) {
		user_topline.setUpdateAppNum(num);
	}
}
